<script>
	// websocket 接口配置
	import {
		WEBSOCKET
	} from "@/common/config.js";
	import md5 from "@/common/utils/md5.js"
	import Vue from 'vue';
	import {
		navigateToLogin
	} from '@/common/utils/utils.js'; 
	export default {
		onLaunch: function() {
			this.$store.commit("initApp");
			uni.getSystemInfo({ 
				success: function(e) {
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight;
					if (e.platform == 'android') {
						Vue.prototype.CustomBar = e.statusBarHeight + 50;
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 45;
					};
					// #endif
					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = e.statusBarHeight;
					let custom = wx.getMenuButtonBoundingClientRect();
					Vue.prototype.Custom = custom;
					Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
					// #endif
					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight;
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
					// #endif
					Vue.mixin({
						data() {
							return {
								StatusBar: Vue.prototype.StatusBar,
								CustomBar: Vue.prototype.CustomBar,
							}
						}
					})
				}
			});
			// #ifdef APP-PLUS
			// 锁定屏幕显示方向为竖屏正方向
			plus.screen.lockOrientation('portrait-primary');
			// #endif
			global.token && this.$store.dispatch('getCartList');

			if(uni.getStorageSync('timInfo')) {
				let config = uni.getStorageSync('timInfo');
				uni.$chat_userID = config.userID;
				uni.$chat_SDKAppID = config.SDKAppID;
				uni.$chat_secretKey = config.secretKey;
			}
		},
		onShow: function() {
			console.log('APP Show');
			// #ifdef APP-PLUS
			// 获取参数
			const args = plus.runtime.arguments;
			if (args) {
				let params_str = args.split('?')[1];
				if (params_str) {
					let params = params_str.split('&').reduce(function(total, item) {
						let arr = item.split('=');
						total[arr[0]] = arr[1];
						return total;
					}, {});
					// params 参数: path 跳转路径 options 参数
					uni.navigateTo({
						url: `${params.path}?goods_id=${params.goods_id}&activity_id=${params.activity_id}&sku_id=${params.sku_id}&bargain_id=${params.bargain_id}`
					})
				}
			}
			// #endif
		},
		onHide: function() {
			// 用户退出app时，把二次验证状态改为true
			console.log('APP Hide');
		},
		watch: {
			'$store.getters.isLogin'(val) {
				if (val) {
					// this.connectSocket()
				} else {
					if (this.$socketTask) {
						this.$socketTask.close();
					}
				}
			}
		},
		methods: {
			getMessageNum() {
				// getMessageNum
				console.log(global.apiUrls, 'global')
				this.$api.post(global.apiUrls.postMessageNum, {
					// id: id
				}).then(res => {
					console.log(res, '消息');
					if (res.data.code == 1) {
						// this.customer = res.data;
						if(true) {
							uni.setTabBarBadge({
								index: 1,
								text: "99+", 
							});
						} else {
							uni.removeTabBarBadge({
								index: 1, 
								text: "",
							});
						}
					}
				});
			},
			//  连接websocket
			connectSocket() {
				console.log('创建websocket')
				let socketTask = uni.connectSocket({
					url: WEBSOCKET,
					success: () => {}
				});
				// 监听websocket是否开启
				let so = socketTask.onOpen(() => {
					console.log('连接开启')

					let data = uni.getStorageSync('USER_INFO');
					console.log(data, 111)


					if (data && data.signature) {
						//登录
						let user_login = JSON.stringify({
							type: 'serviceApi',
							unLogin: 'unLogin',
							serviceApiName: 'getCustomerServiceInfo',
							requestsParams: {
								signature: data.signature,
								token: md5(this.$util.timeFormat(null, 'yyyymmdd') + 'zhongbenkeji')
							}
						})
						this.sendSocketMessage(socketTask, user_login)
					}
				})
				// 全局接收消息
				socketTask.onMessage(res => {
					var data = JSON.parse(res.data);
					// console.log(data, data.code, 'code999')
					switch (data.message_type) {
						// 服务端ping客户端
						case 'ping':
							this.sendSocketMessage(socketTask, '{"type":"ping"}');
							break;
						case 'chatMessage':
							// console.log(data)
							this.$store.commit('addMeassageChatInfo', data.data)
							// 接收消息震动
							this.getMessageNum()
							uni.vibrateLong();
							break;
						case 'readMessage':
							this.$store.commit('readMessage', data.data.ids)
							break;
						case 'messageSuccess':
							this.$store.commit('messageSuccess', data.data)
							break;
						case 'init':
							console.log('注册接口', data.data)
							break;
						case 'userLogin':
							console.log('userLogin', data.data)
							break;
					}
					if (data.code == 1) { 
						console.log('请求返回数据', data.data)
						//请求接口
						switch (data.data.type) {
							case 'serviceApi':
								switch (data.data.serviceApiName) {
									// 消息列表
									case 'getCustomerServiceUserList':
										console.log('消息列表', data)
										this.$store.commit('updateChatUsersList', data.data.list)
										break;
										// 聊天记录
									case 'getMeassageChatList':
										this.$store.commit('updateMeassageChatList', data.data.list)
										break;
										// 登录
									case 'getCustomerServiceInfo':
										this.$store.commit('addSocketLoginInfo', data.data)
										this.socketGetUserInfo(data.data)
										break;

								}
								break;
						}
					}
				})

				socketTask.onError(res => {
					this.$store.commit('updateSocketOpen', false)
					setTimeout(() => {
						// 重新连接
						this.connectSocket()
					}, 4000);
				})

				Vue.prototype.$socketTask = socketTask
			},
			//注册
			socketGetUserInfo(data) {
				let user_data_init = JSON.stringify({
					type: 'init',
					partner_id: data.partner_id,
					uid: 'KF' + data.id,
					service_number: data.service_number,
					name: data.nickname,
					avatar: data.avatar,
					group_id: data.group,
				})
				this.sendSocketMessage(this.$socketTask, user_data_init)
				this.$store.commit('updateSocketOpen', true)

			},
			// 发送信息
			sendSocketMessage(socketTask, msg) {
				socketTask.send({
					data: msg,
					success: (res) => {
						// console.log(res);
					},
					fail: function(res) {
						// console.log(res);
					}
				})
			},
			// 推送回调
			pushCallback(message) {
				console.log("to do list", message);
			},
			// #ifdef APP-PLUS
			// 权限检查
			checkPermissions() {
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android') { // 判断是Android
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					var NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
					// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置
					if (!areNotificationsEnabled) {
						this.$util.showModal({
							title: '通知权限开启提醒',
							content: '您还没有开启通知权限，无法接受到消息通知，是否前往设置？',
							success: function(res) {
								if (res.confirm) {
									var Intent = plus.android.importClass('android.content.Intent');
									var Build = plus.android.importClass("android.os.Build");
									//android 8.0引导
									if (Build.VERSION.SDK_INT >= 26) {
										var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
										intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
									} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0
										var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
										intent.putExtra("app_package", pkName);
										intent.putExtra("app_uid", uid);
									} else { //(<21)其他--跳转到该应用管理的详情页
										intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
										var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
										intent.setData(uri);
									}
									// 跳转到该应用的系统通知设置页
									main.startActivity(intent);
								}
							}
						});
					}
				} else if (plus.os.name == 'iOS') { // 判断是ISO
					var isOn = undefined;
					var types = 0;
					var app = plus.ios.invoke('UIApplication', 'sharedApplication');
					var settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
					if (settings) {
						types = settings.plusGetAttribute('types');
						plus.ios.deleteObject(settings);
					} else {
						types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
					}
					plus.ios.deleteObject(app);
					isOn = (0 != types);
					if (isOn == false) {
						this.$util.showModal({
							title: '通知权限开启提醒',
							content: '您还没有开启通知权限，无法接受到消息通知，是否前往设置？',
							success: function(res) {
								if (res.confirm) {
									var app = plus.ios.invoke('UIApplication', 'sharedApplication');
									var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
									plus.ios.invoke(app, 'openURL:', setting);
									plus.ios.deleteObject(setting);
									plus.ios.deleteObject(app);
								}
							}
						});
					}
				}
				// #endif
			},
			// 初始化 3D Touch
			init3DTouch() {
				this.$api.post(global.apiUrls.postHomeGrid, {
					typeid: 2
				}).then(res => {
					if (res.data.code == 1) {
						let list = res.data.data;
						const dcRichAlert = uni.requireNativePlugin('DCloud-RichAlert');
						if (dcRichAlert) {
							let _shortcut = '[';
							let len = list.length;
							list.forEach((item, index) => {
								_shortcut +=
									`{"id":"${item.href}","describe":"${item.name}","icon":"${item.thumb}","shortlabel":"${item.name}","longlabel":"${item.name}"}`;
								if ((index + 1) != len) {
									_shortcut += ','
								}
							})
							_shortcut += ']';
							dcRichAlert.show({
								shortcut: _shortcut
							}, result => {
								if (result.post === 'success') {
									uni.navigateTo({
										url: result.id
									})
								}
							});
						}
					}
				});
			}
			// #endif
		}
	}
</script>



<style>
	/* #ifndef APP-PLUS-NVUE */
	@import "./style/icon.css";
	@import "./style/main.css";
	@import "./style/animation.css";
	/* @import "./style/iconfont.css"; */
	@import "./style/common.scss";
	/* #endif */
	
	/* 推广 */
	.statisticsBgColor {
		background: #f94032;
		color: #FFFFFF;
	}

	
</style>
<style lang="scss">
	/* #ifndef APP-PLUS-NVUE */
	@import "./style/common.scss";
	/* #endif */
	
	/* 推广 */
	.statisticsBgColor {
		background: #f94032;
		color: #FFFFFF;
	}
	/*  ===========我的资料============ start */
	/* uni-actionshee    start */
	.uni-actionsheet__menu .uni-actionsheet__cell {
		color: #333333 !important;
	}
	
	.uni-actionsheet__action .uni-actionsheet__cell {
		color: #FF6464 !important;
	}
	
	/* uni-actionshee end */
	/*  picker start */
	
	.uni-picker-container .uni-picker-action.uni-picker-action-confirm {
		color: #FF6464;
	}
	
	/*  picker end */
	/*  ===========我的资料============ end */
</style>
